<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    @close="dialogClose"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="组名" prop="name">
      <el-input v-model="dataForm.name" placeholder="组名"></el-input>
    </el-form-item>
    <el-form-item label="排序" prop="sort">
      <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
    </el-form-item>
    <el-form-item label="说明" prop="description">
      <el-input v-model="dataForm.description" placeholder="说明"></el-input>
    </el-form-item>
    <el-form-item label="组图标" prop="icon">
      <el-input v-model="dataForm.icon" placeholder="组图标"></el-input>
    </el-form-item>
    <el-form-item label="所属分类id" prop="categoryId">
      <!--
        1.添加选择所属分类ID时,使用cascader级联选择器
        2.v-model记录三级分类全部id
        3.options表示级联显示的时候各个层的选型是从categorys数组来的
        4.props显示的分别和返回的category的对象的哪些字段关联
        5.filterable,placeholder="搜索" 在级联选择器增加搜索功能
      -->
      <el-cascader
        filterable
        placeholder="搜索: "
        v-model="cascadeCategoryId"
        :options="categories"
        :props="props"
        ></el-cascader>
<!--      <el-input v-model="dataForm.categoryId" placeholder="所属分类id"></el-input>-->
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        categories: [],
        cascadeCategoryId:[], //[1,101,1001]
        props:{
          value: "id",
          label: "name",
          children: "childrenCategories"
        },
        visible: false,
        dataForm: {
          id: 0,
          name: '',
          sort: '',
          description: '',
          icon: '',
          categoryId: 0 //默认给categoryId=0,这里前端人员可以根据需求来处理
        },
        dataRule: {
          name: [
            { required: true, message: '组名不能为空', trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '排序不能为空', trigger: 'blur' }
          ],
          description: [
            { required: true, message: '说明不能为空', trigger: 'blur' }
          ],
          icon: [
            { required: true, message: '组图标不能为空', trigger: 'blur' }
          ],
          categoryId: [
            { required: true, message: '所属分类id不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      this.getCategories() //第一次进入该页面,就调用方法
    },
    methods: {
      //增加方法,清空 this.cascadeCategoryId
      dialogClose() {
        this.cascadeCategoryId = []
      },
      //增加方法,返回所有的分类信息
      // 获取数据列表,带层级
      getCategories () {
        this.$http({
          // url: this.$http.adornUrl('/commodity/category/list'),
          // url: 'http://localhost:9090/commodity/category/list',
          // url就是 http://localhost:5050/api + /commodity/category/list
          url: this.$http.adornUrl('/commodity/category/list'),
          method: 'get'
        }).then(({data}) => { // {data}解构了返回数据的data部分
          console.log('拿到的数据', data)
          //将返回的层级关系的数据和this.categories绑定
          this.categories = data.data
        })
      },
      init (id) {
        //因为级联选择器,在展示分类层级时,依据 cascadeCategoryId
        console.log("cascadeCategoryId->",this.cascadeCategoryId)
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/commodity/attrgroup/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.attrgroup.name
                this.dataForm.sort = data.attrgroup.sort
                this.dataForm.description = data.attrgroup.description
                this.dataForm.icon = data.attrgroup.icon
                this.dataForm.categoryId = data.attrgroup.categoryId
                //每次点击修改,能够对应显示分类层级,需要获取到对应的cascadeCategoryId
                this.cascadeCategoryId = data.attrgroup.cascadeCategoryId
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          //输出cascadeCategoryId
          //console.log("cascadeCategoryId=",this.cascadeCategoryId)

          //给this.dataForm.categoryId赋值,用户点击级联信息的三级分类id

          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/commodity/attrgroup/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'sort': this.dataForm.sort,
                'description': this.dataForm.description,
                'icon': this.dataForm.icon,
                //'categoryId': this.dataForm.categoryId
                //说明:cascadeCategoryId保存了当前用户选择的分类的各层级id
                //[1,101,1001],而真正要提交的是1001,即数组的最后一个元素
                'categoryId': this.cascadeCategoryId[this.cascadeCategoryId.length-1]
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
